# coding:utf-8
from odoo import models, fields, api, _
from odoo.exceptions import Warning
from datetime import datetime, timedelta


class PaulSaleOrderExtend(models.Model):
    _name = 'sale.order'
    _inherit = ["sale.order"]

    partner_address = fields.Char(' ')
    partner_invoice_address = fields.Char(' ')
    partner_shipping_address = fields.Char(' ')

    is_copy = fields.Boolean('Is Copy', default=False, copy=False)

    @api.onchange('partner_id')
    def _onchange_partner_id(self):
        if self.partner_id:
            self.partner_address = self.partner_id._display_address(without_company=True)
        else:
            self.partner_address = False

        return {
            'domain': {'pricelist_id': [('id', 'in', self.property_product_pricelist_ids.ids)], 'payment_term_id': [('id', 'in', self.customer_payment_term_ids.ids)]},
        }

    @api.onchange('partner_invoice_id', 'partner_shipping_id')
    def _onchange_invoice_and_shipping_partner_id(self):
        if self.partner_shipping_id:
            self.partner_shipping_address = self.partner_shipping_id._display_address(without_company=True)
        else:
            self.partner_shipping_address = False

        if self.partner_invoice_id:
            self.partner_invoice_address = self.partner_invoice_id._display_address(without_company=True)
        else:
            self.partner_invoice_address = False

    @api.multi
    def write(self, vals):
        if self.is_copy is True:
            for line_c in self.order_line_clone:
                for line in self.order_line:
                    if line.id == line_c.origin_id:
                        line.price_unit = line_c.price_unit
        if vals.get('partner_id', False):
            vals['partner_address'] = self.env['res.partner'].search([('id', '=', vals['partner_id'])])._display_address(without_company=True)
        if vals.get('partner_shipping_id', False):
            vals['partner_shipping_address'] = self.env['res.partner'].search([('id', '=', vals['partner_shipping_id'])])._display_address(without_company=True)
        if vals.get('partner_invoice_id', False):
            vals['partner_invoice_address'] = self.env['res.partner'].search([('id', '=', vals['partner_invoice_id'])])._display_address(without_company=True)
        return super(PaulSaleOrderExtend, self).write(vals)

    @api.model
    def create(self, vals):
        vals['partner_address'] = self.env['res.partner'].search([('id', '=', vals['partner_id'])])._display_address(without_company=True)
        vals['partner_shipping_address'] = self.env['res.partner'].search([('id', '=', vals['partner_shipping_id'])])._display_address(without_company=True)
        vals['partner_invoice_address'] = self.env['res.partner'].search([('id', '=', vals['partner_invoice_id'])])._display_address(without_company=True)
        res = super(PaulSaleOrderExtend, self).create(vals)
        return res
